package com.ruoyi.oauth.wx.service.Impl;

import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.auth.common.domain.OauthUser;
import com.ruoyi.auth.common.service.IOauthUserService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpClientUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.oauth.wx.constant.WxMiniAppConstant;
import com.ruoyi.oauth.wx.service.WxLoginService;
import com.ruoyi.system.service.ISysUserService;

@Service
public class WxMiniAppLoginServiceImpl implements WxLoginService {
    @Autowired
    private WxMiniAppConstant wxAppConstant;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IOauthUserService oauthUserService;

    @Override
    public String doLogin(String code) {
        String openid = doAuth(
                wxAppConstant.getUrl(),
                wxAppConstant.getAppId(),
                wxAppConstant.getAppSecret(),
                code).getString("openid");
        OauthUser selectOauthUser = oauthUserService.selectOauthUserByUUID(openid);
        if (selectOauthUser == null) {
            return null;
        }
        SysUser sysUser = userService.selectUserById(selectOauthUser.getUserId());
        if (sysUser == null) {
            throw new ServiceException("该微信未绑定用户");
        }
        LoginUser loginUser = (LoginUser) userDetailsServiceImpl.createLoginUser(sysUser);
        return tokenService.createToken(loginUser);
    }

    @Override
    public String doRegister(OauthUser oauthUser) {
        if (StringUtils.isEmpty(oauthUser.getCode())) {
            return "没有凭证";
        }
        if (oauthUser.getUserId() == null) {
            return "请先注册账号";
        }
        JSONObject doAuth = doAuth(
                wxAppConstant.getUrl(),
                wxAppConstant.getAppId(),
                wxAppConstant.getAppSecret(),
                oauthUser.getCode());
        oauthUser.setOpenId(doAuth.getString("openid"));
        oauthUser.setUuid(doAuth.getString("openid"));
        oauthUser.setSource("WXMiniApp");
        oauthUser.setAccessToken(doAuth.getString("session_key"));
        oauthUserService.insertOauthUser(oauthUser);
        return "";
    }

    /**
     * 获取微信手机号
     * @param code 动态令牌
     * @return 手机号
     */
    public String getPhoneNumber(String code) {
        // 获取access_token
        String accessToken = getAccessToken();
        
        // 调用微信接口获取手机号
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        
        JSONObject requestBody = new JSONObject();
        requestBody.put("code", code);
        
        String result = HttpClientUtil.sendHttpPost(url, requestBody.toJSONString());
        JSONObject jsonObject = JSON.parseObject(result);
        
        if (jsonObject.getIntValue("errcode") == 0) {
            JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
            return phoneInfo.getString("phoneNumber");
        } else {
            throw new ServiceException("获取手机号失败: " + jsonObject.getString("errmsg"));
        }
    }
    
    /**
     * 获取access_token
     * @return access_token
     */
    private String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        StringBuilder builder = new StringBuilder(url);
        builder.append("?grant_type=client_credential")
                .append("&appid=").append(wxAppConstant.getAppId())
                .append("&secret=").append(wxAppConstant.getAppSecret());
        
        String result = HttpClientUtil.sendHttpGet(builder.toString());
        JSONObject jsonObject = JSON.parseObject(result);
        
        if (jsonObject.containsKey("access_token")) {
            return jsonObject.getString("access_token");
        } else {
            throw new ServiceException("获取access_token失败: " + jsonObject.getString("errmsg"));
        }
    }
}
